<script setup>
import { ref } from 'vue'
import axios from 'axios'

const dialogVisible = ref(false)
const inputQuestion = ref('')
const messages = ref([])
const isLoading = ref(false)

const openDialog = () => {
  dialogVisible.value = true
}

const sendQuestion = async () => {
  if (!inputQuestion.value.trim() || isLoading.value) return
  
  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: inputQuestion.value
  })
  
  const question = inputQuestion.value
  inputQuestion.value = ''
  isLoading.value = true
  
  try {
      // 此处配置的的后端访问地址
    const response = await axios.post('http://localhost:8888/api/ask', {
      question: question
    })
    
    // 添加AI回复
    messages.value.push({
      role: 'assistant',
      content: response.data.answer
    })
  } catch (error) {
    console.error('Error:', error)
    messages.value.push({
      role: 'assistant',
      content: '抱歉，获取回答时出错。'
    })
  } finally {
    isLoading.value = false
  }
}

defineExpose({
  openDialog
})
</script>

<template>
  <el-dialog v-model="dialogVisible" title="DeepSeek问答" width="70%">
    <div class="chat-container">
      <div 
        v-for="(message, index) in messages" 
        :key="index" 
        class="message" 
        :class="{ 
          'user-message': message.role === 'user', 
          'ai-message': message.role === 'assistant' 
        }"
      >
        <div class="message-content">{{ message.content }}</div>
      </div>
      <div v-if="isLoading" class="loading-indicator">
        <el-icon class="is-loading"><Loading /></el-icon>
        思考中...
      </div>
    </div>
    <template #footer>
      <div class="input-area">
        <el-input 
          v-model="inputQuestion" 
          placeholder="请输入您的问题..." 
          @keyup.enter="sendQuestion" 
          :disabled="isLoading"
        />
        <el-button 
          type="primary" 
          @click="sendQuestion" 
          :loading="isLoading"
        >
          发送
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.chat-container {
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  position: relative;
}

.message {
  margin-bottom: 15px;
  padding: 10px;
  border-radius: 8px;
  max-width: 80%;
}

.user-message {
  background-color: #f0f7ff;
  margin-left: auto;
  text-align: right;
}

.ai-message {
  background-color: #f5f5f5;
  margin-right: auto;
}

.message-content {
  white-space: pre-wrap;
}

.input-area {
  display: flex;
  gap: 10px;
}

.loading-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #999;
  padding: 8px;
}
</style>